package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadLocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    WmNewsMaterialService wmNewsMaterialService;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) throws IOException {
        //1.参数判断
        //1.1空-抛异常
        if(multipartFile==null)
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_NOT_NULL);
        }

        //2.1获取文件后缀
        int index = multipartFile.getOriginalFilename().lastIndexOf(".");
        if(index==-1)
        {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        String suffix=multipartFile.getOriginalFilename().substring(index);
        //3.生成文件名
        String fileName= UUID.randomUUID().toString().replace("-","")+suffix;
        //4.上传文件
        String url = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
        //5.封装数据保存并放回
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUserId());
        wmMaterial.setType(WmMaterial.Type.PICTURE);
        wmMaterial.setIsCollection(WmMaterial.CollectionStatus.NO_COLLECTION);
        wmMaterial.setUrl(url);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数
        //1.1空-抛出异常
        if(dto==null)
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_NOT_NULL);
        }
        dto.checkParam();
        //2.按照用户id,是否收藏，分页，排序
        LambdaQueryWrapper<WmMaterial> lqw=new LambdaQueryWrapper<>();
        lqw.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUserId())
                .eq(dto.getIsCollection()!=null&&dto.getIsCollection().equals(WmMaterial.CollectionStatus.IS_COLLECTION.getValue()),WmMaterial::getIsCollection,dto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime);
        IPage page=new Page(dto.getPage(),dto.getSize());
        page= this.page(page, lqw);

        //3.返回
        return ResponseResult.okResult(page);
    }

    @Override
    public ResponseResult collect(Integer wmMaterialId) {
        //1.参数判断
        if(wmMaterialId==null)
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_NOT_NULL);
        }
        //2.根据id查询素材
        WmMaterial material = this.getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, wmMaterialId));
        //3.素材是否为空
        //3.1空-抛异常
        if(material==null)
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_EXCEPTION);
        }
        //4.修改状态，保存，返回成功信息
        if(material.getIsCollection().equals(WmMaterial.CollectionStatus.IS_COLLECTION.getValue()))
        {
            material.setIsCollection(WmMaterial.CollectionStatus.NO_COLLECTION);
        }
        else{
            material.setIsCollection(WmMaterial.CollectionStatus.IS_COLLECTION);
        }
        this.updateById(material);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteById(Integer wmMaterialId) {
        if(wmMaterialId==null)
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_NOT_NULL);
        }
        WmMaterial wmMaterial = this.getById(wmMaterialId);
        if(wmMaterial==null)
        {
            throw new CustomException(AppHttpCodeEnum.PARAMS_EXCEPTION);
        }
        List<WmNewsMaterial> list = wmNewsMaterialService.list(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, wmMaterialId));
        if (!list.isEmpty())
        {
            throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCED);
        }
        this.removeById(wmMaterialId);
        return ResponseResult.okResult();
    }
}
